<!-- components/reconciliation/MatchDetailsDrawer.vue -->
<template>
  <el-drawer
    v-model="visible"
    title="匹配详情"
    size="50%"
    :before-close="handleClose"
  >
    <div class="match-details" v-if="matchData">
      <!-- 基本信息 -->
      <el-card class="info-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>基本信息</span>
          </div>
        </template>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <span class="label">匹配ID:</span>
              <span class="value">{{ matchData.id }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <span class="label">匹配状态:</span>
              <el-tag :type="statusTagType">{{ statusText }}</el-tag>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <span class="label">匹配类型:</span>
              <el-tag :type="matchTypeTagType">{{ matchTypeText }}</el-tag>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <span class="label">置信度:</span>
              <ConfidenceIndicator 
                :confidence="matchData.matchInfo.confidence"
                :status="matchData.matchInfo.matchStatus"
              />
            </div>
          </el-col>
        </el-row>
      </el-card>
      
      <!-- 订单信息 -->
      <el-card class="info-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>订单信息</span>
          </div>
        </template>
        
        <el-descriptions :column="1" border>
          <el-descriptions-item label="订单号">{{ matchData.orderInfo.platformOrderId }}</el-descriptions-item>
          <el-descriptions-item label="客户名称">{{ matchData.orderInfo.customerName }}</el-descriptions-item>
          <el-descriptions-item label="订单金额">¥{{ matchData.orderInfo.orderAmount.toLocaleString() }}</el-descriptions-item>
          <el-descriptions-item label="订单日期">{{ formatDate(matchData.orderInfo.orderDate) }}</el-descriptions-item>
          <el-descriptions-item label="发票状态">
            <el-tag :type="invoiceStatusType">{{ invoiceStatusText }}</el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>
      
      <!-- 银行流水信息 -->
      <el-card class="info-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>银行流水信息</span>
          </div>
        </template>
        
        <el-descriptions :column="1" border>
          <el-descriptions-item label="流水号">{{ matchData.transactionInfo.transactionId }}</el-descriptions-item>
          <el-descriptions-item label="付款人">{{ matchData.transactionInfo.payerName }}</el-descriptions-item>
          <el-descriptions-item label="流水金额">¥{{ matchData.transactionInfo.transactionAmount.toLocaleString() }}</el-descriptions-item>
          <el-descriptions-item label="流水时间">{{ formatDateTime(matchData.transactionInfo.transactionDate) }}</el-descriptions-item>
          <el-descriptions-item label="银行名称">{{ matchData.transactionInfo.bankName }}</el-descriptions-item>
        </el-descriptions>
      </el-card>
      
      <!-- 匹配算法分析 -->
      <el-card class="info-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>匹配算法分析</span>
          </div>
        </template>
        
        <div class="algorithm-info">
          <div class="algorithm-item">
            <span class="label">使用算法:</span>
            <span class="value">{{ algorithmText }}</span>
          </div>
          <div class="algorithm-item">
            <span class="label">匹配时间:</span>
            <span class="value">{{ formatDateTime(matchData.matchInfo.matchedAt) }}</span>
          </div>
          <div v-if="matchData.matchInfo.confirmedAt" class="algorithm-item">
            <span class="label">确认时间:</span>
            <span class="value">{{ formatDateTime(matchData.matchInfo.confirmedAt) }}</span>
          </div>
        </div>
        
        <!-- 因素分析 -->
        <div class="factors-analysis">
          <h4>因素分析</h4>
          <el-table :data="matchData?.reasoning?.factors || []" style="width: 100%">
            <el-table-column prop="factor" label="因素" width="150">
              <template #default="{ row }">
                {{ factorTextMap[row.factor] || row.factor }}
              </template>
            </el-table-column>
            <el-table-column prop="score" label="得分" width="100">
              <template #default="{ row }">
                {{ row.score }}分
              </template>
            </el-table-column>
            <el-table-column prop="weight" label="权重" width="100">
              <template #default="{ row }">
                {{ (row.weight * 100).toFixed(0) }}%
              </template>
            </el-table-column>
            <el-table-column prop="description" label="说明" />
          </el-table>
          <div class="total-score">
            <strong>总分: {{ matchData?.reasoning?.totalScore || 0 }}分</strong>
          </div>
        </div>
      </el-card>
      
      <!-- 差异信息 -->
      <el-card class="info-card" shadow="never" v-if="matchData?.differenceInfo?.hasDifferences">
        <template #header>
          <div class="card-header">
            <span>差异信息</span>
          </div>
        </template>
        
        <el-alert
          title="此匹配存在差异，请仔细核对"
          type="warning"
          show-icon
          :closable="false"
        />
        
        <div class="differences-info">
          <el-row :gutter="20">
            <el-col :span="12" v-if="matchData?.differenceInfo?.amountDiff">
              <div class="difference-item">
                <span class="label">金额差异:</span>
                <span class="value danger">¥{{ matchData.differenceInfo.amountDiff?.toFixed(2) || '0.00' }}</span>
              </div>
            </el-col>
            <el-col :span="12" v-if="matchData?.differenceInfo?.dateDiff">
              <div class="difference-item">
                <span class="label">时间差异:</span>
                <span class="value warning">{{ matchData.differenceInfo.dateDiff }}天</span>
              </div>
            </el-col>
            <el-col :span="12" v-if="matchData?.differenceInfo && matchData.differenceInfo.nameSimilarity < 100">
              <div class="difference-item">
                <span class="label">名称相似度:</span>
                <span class="value">{{ matchData.differenceInfo.nameSimilarity }}%</span>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-card>
    </div>
    
    <!-- 操作按钮 -->
    <template #footer>
      <div class="drawer-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button 
          type="success" 
          @click="handleConfirm"
          :disabled="matchData?.matchInfo.matchStatus !== 'pending'"
          v-if="showActions"
        >
          确认匹配
        </el-button>
        <el-button 
          type="danger" 
          @click="handleReject"
          :disabled="matchData?.matchInfo.matchStatus !== 'pending'"
          v-if="showActions"
        >
          拒绝匹配
        </el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import type { ReconciliationResult } from '@/types/reconciliation'
import ConfidenceIndicator from './ConfidenceIndicator.vue'

const props = defineProps<{
  modelValue: boolean
  matchData: ReconciliationResult | null
  showActions?: boolean
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'confirm', match: ReconciliationResult): void
  (e: 'reject', match: ReconciliationResult): void
}>()

const visible = computed({
  get: () => props.modelValue,
  set: (value: boolean) => emit('update:modelValue', value)
})

const statusTagType = computed(() => {
  if (!props.matchData) return 'info'
  switch (props.matchData.matchInfo.matchStatus) {
    case 'confirmed': return 'success'
    case 'pending': return 'warning'
    case 'rejected': return 'danger'
    default: return 'info'
  }
})

const statusText = computed(() => {
  if (!props.matchData) return ''
  switch (props.matchData.matchInfo.matchStatus) {
    case 'confirmed': return '已确认'
    case 'pending': return '待确认'
    case 'rejected': return '已拒绝'
    default: return '未知'
  }
})

const matchTypeTagType = computed(() => {
  if (!props.matchData) return 'info'
  return props.matchData.matchInfo.matchType === 'auto' ? 'success' : 'warning'
})

const matchTypeText = computed(() => {
  if (!props.matchData) return ''
  return props.matchData.matchInfo.matchType === 'auto' ? '自动匹配' : '手动匹配'
})

const invoiceStatusType = computed(() => {
  if (!props.matchData) return 'info'
  switch (props.matchData.orderInfo.invoiceStatus) {
    case 'invoiced': return 'success'
    case 'pending': return 'warning'
    case 'cancelled': return 'danger'
    default: return 'info'
  }
})

const invoiceStatusText = computed(() => {
  if (!props.matchData) return ''
  switch (props.matchData.orderInfo.invoiceStatus) {
    case 'invoiced': return '已开票'
    case 'pending': return '待开票'
    case 'cancelled': return '已取消'
    default: return props.matchData.orderInfo.invoiceStatus
  }
})

const algorithmText = computed(() => {
  if (!props.matchData) return ''
  const algorithmMap: Record<string, string> = {
    'exact_match': '精确匹配',
    'amount_first': '金额优先',
    'time_window': '时间窗口',
    'comprehensive': '综合算法'
  }
  return algorithmMap[props.matchData.matchInfo.matchAlgorithm] || props.matchData.matchInfo.matchAlgorithm
})

const factorTextMap = {
  'amount_match': '金额匹配',
  'name_similarity': '名称相似度',
  'time_proximity': '时间接近度',
  'bank_verification': '银行验证',
  'historical_pattern': '历史模式'
}

const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleDateString('zh-CN')
}

const formatDateTime = (dateTimeString: string) => {
  const date = new Date(dateTimeString)
  return `${date.toLocaleDateString('zh-CN')} ${date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })}`
}

const handleClose = () => {
  visible.value = false
}

const handleConfirm = () => {
  if (props.matchData) {
    emit('confirm', props.matchData)
  }
}

const handleReject = () => {
  if (props.matchData) {
    emit('reject', props.matchData)
  }
}
</script>

<style scoped>
.match-details {
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.info-card {
  flex: 1;
}

.card-header {
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.label {
  width: 80px;
  color: var(--el-text-color-secondary);
  margin-right: 12px;
}

.value {
  font-weight: 500;
}

.value.danger {
  color: var(--el-color-danger);
}

.value.warning {
  color: var(--el-color-warning);
}

.algorithm-info {
  margin-bottom: 20px;
}

.algorithm-item {
  display: flex;
  margin-bottom: 8px;
}

.algorithm-item .label {
  width: 100px;
}

.factors-analysis h4 {
  margin: 0 0 12px 0;
  color: var(--el-text-color-primary);
}

.total-score {
  text-align: right;
  margin-top: 12px;
  font-size: 16px;
}

.differences-info {
  margin-top: 16px;
}

.difference-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.difference-item .label {
  width: 100px;
}

.drawer-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>